<?php
/**
 * 通用请求
 * User: 13651
 * Time: 2025/9/5 11:37
 */

namespace App\Traits;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Psr\Http\Message\ResponseInterface;

trait HttpHelper
{
    /**
     * 发送post json请求
     * @param string $url 请求地址
     * @param $data 请求数据
     * @param array $proxy 代理端口
     * @param array $header 请求头信息
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function sendPost(string $url, $data, array $proxy = [], array $header = [])
    {
        $client = new Client(["verify"=>false, 'timeout' => 30]);
        $headers = !empty($header) ? $header : ['Content-Type' => 'application/json;charset=utf-8'];

        $response = $client->post($url, [
            'json' => $data,
            'headers' => $headers,
            'proxy' => $proxy,
        ]);
        return $response;
    }

    /**
     * 发送post表单请求
     * @param string $url
     * @param array $params
     * @return ResponseInterface
     * @throws \Exception
     */
    public function sendFormDataPost(string $url, array $params)
    {
        try {
            set_time_limit(0);
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            $header = array('Content-Type:multipart/form-data');//请求头记得变化-不同的上传方式
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        }catch (\Exception $e){
            Log::info('发送请求至第三方异常:'.$e->getMessage());
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 发送 post form-data 请求
     *
     * @param string $url
     * @param array $data
     * @param array $proxy = []
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function sendFormDataFilePost(string $url, array $data, array $proxy = [])
    {
        $client = new Client(["verify"=>false, 'timeout' => 30]);
        $response = $client->post($url, [
            'form_params' => $data,
            'proxy' => $proxy
        ]);
        return $response;
    }
}